package org.misty.practices.jedis;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;

import java.util.HashSet;

public class Cluster {
  public static void main(String[] args) {
    var nodeList = new HashSet<HostAndPort>();
    nodeList.add(new HostAndPort("127.0.0.1", 7000));
    nodeList.add(new HostAndPort("127.0.0.1", 7001));
    nodeList.add(new HostAndPort("127.0.0.1", 7002));
    nodeList.add(new HostAndPort("127.0.0.1", 7003));
    nodeList.add(new HostAndPort("127.0.0.1", 7004));
    nodeList.add(new HostAndPort("127.0.0.1", 7005));

    var poolConfig = new GenericObjectPoolConfig<>();
    poolConfig.setMaxTotal(10);

    var redisCluster = new JedisCluster(nodeList, 30000, poolConfig);
    redisCluster.set("hello", "world");
    System.out.println(redisCluster.get("hello"));

    var poolMap = redisCluster.getClusterNodes();
    for (var entry : poolMap.entrySet()) {
      try (var jedis = entry.getValue().getResource();) {
        if (!isMaster(jedis)) {
          continue;
        }
        jedis.del("hello");
      }
    }

    redisCluster.close();
  }

  public static boolean isMaster(Jedis jedis) {
    // 通过redis命令 role 或者 info 解析
    return true;
  }
}
